package models

import (
	"github.com/jinzhu/gorm"
	_ "github.com/go-sql-driver/mysql"
	"TeacherManager/system"
	"fmt"
	"TeacherManager/common"
)

/**
* Created by LONG  on 2018/5/25.
*/

var DB *gorm.DB

//table users
type User struct {
	BaseModel
	Email       string `gorm:"unique_index;default:null"` //邮箱
	Telephone   string `gorm:"unique_index;default:null"` //手机号码
	Password    string `gorm:"default:null"`              //密码
	VerifyState string `gorm:"default:'0'"`               //邮箱验证状态
	SecretKey   string `gorm:"default:null"`              //密钥
	IsAdmin     bool                                      //是否是管理员
	AvatarUrl   string                                    // 头像链接
	NickName    string                                    // 昵称
}

func (User) TableName() string {
	return "users"
}

func InitDB() (*gorm.DB, error) {

	db, err := gorm.Open("mysql", system.GetConfiguration().DSN)
	//db, err := gorm.Open("mysql", "root:mysql@/wblog?charset=utf8&parseTime=True&loc=Asia/Shanghai")
	fmt.Println(db)
	fmt.Println(err)
	if err == nil {
		DB = db

		//db.LogMode(true) 设置数据库日志模式为啥都输出
		////自动生成表
		db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8").AutoMigrate(&User{},
			&Class{}, &Student{}, &Exam{}, &ExamScore{},&Notice{})
		//gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
		//	return  system.GetConfiguration().Dbprefix + defaultTableName
		//}
		//建立博文与标签的唯一索引
		//db.Model(&PostTag{}).AddUniqueIndex("uk_post_tag", "post_id", "tag_id")
		//初始化管理员
		initAdmin()
		return db, err
	}
	return nil, err
}

//初始化管理员
func initAdmin() {
	user, _ := GetUserByUsername("1762648394@qq.com")

	if user.ID == 0 {
		u := User{
			Email:     "1762648394@qq.com",
			Password:  "123456",
			IsAdmin:   true,
			NickName:  "管理员",
			AvatarUrl: "http://p983g78xf.bkt.clouddn.com/constructocat2.jpg",
		}

		u.HashPassword()

		DB.Save(&u)
	}
}

func GetUserByUsername(username string) (*User, error) {
	var user User
	err := DB.First(&user, "email = ?", username).Error
	return &user, err
}
func GetUser(id interface{}) (*User, error) {
	var user User
	err := DB.Where("id = ?", id).First(&user).Error
	return &user, err
}

func (user *User) HashPassword() {
	user.Password = common.Md5(user.Email + user.Password)
}

// user
// insert user
func (user *User) Insert() error {
	return DB.Create(user).Error
}

// update user
func (user *User) Update() error {
	return DB.Save(user).Error
}

func (user *User) UpdateProfile(email, nickName string) error {
	return DB.Model(user).Update(User{Email: email, NickName: nickName}).Error
}
